Uploading and Reading a CSV File in Flask

您所在的位置:网站首页 flask formdata Uploading and Reading a CSV File in Flask

Uploading and Reading a CSV File in Flask

2023-03-04 22:53| 来源: 网络整理| 查看: 265

Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article, let’s upload a CSV (Comma-Separated Values) file and read the contents of the file on a web page of the browser.

Required Module

Install Flask by running the pip command in your terminal. Additionally, you may want to install some popular libraries such as Pandas.

pip install Flask pip install PandasImplementation to Upload and Read the CSV File in Flask Application

Here in this Flask application, we are creating a folder named ‘staticFiles’ to store our uploaded CSV files.

Uploading and Reading a CSV File in Flask

Application File Directory

index.html

Let’s create a user interface (web page) – index.html for uploading the CSV file. 

HTML

      Uploading & Reading CSV file                                   Choose csv file to upload               

Output:

Uploading and Reading a CSV File in Flask

 

index2.html

To let the user know that the file uploaded successfully we are creating another HTML file – index2.html. 

HTML

      Uploading & Reading CSV file                                    File uploaded successfully!!                

Output:

Uploading and Reading a CSV File in Flask

 

show_csv_data.html

We are also creating another HTML file – show_csv_data.html for displaying the data after clicking the Show CSV button.  

HTML

        {{ data_var|safe }}    

Output:

Uploading and Reading a CSV File in Flask

Reading CSV file data in Table Format on a web page

app.py

Launch app.py from the code editor first, then open the deployment server URL in a web browser at http://127.0.0.1:5000. A web page with three buttons鈥擟hoose a file, Upload, and Show CSV鈥攖hen appears. Click the Upload button to upload the CSV file. Then a prompt indicating that the file successfully uploaded displays. To read the file data on the website, select the “Show CSV” button. When you select “Show CSV,” a new tab opens up with your file’s data shown in tabular format.

Python3

from distutils.log import debugfrom fileinput import filenameimport pandas as pdfrom flask import *import osfrom werkzeug.utils import secure_filename UPLOAD_FOLDER = os.path.join('staticFiles', 'uploads') # Define allowed filesALLOWED_EXTENSIONS = {'csv'} app = Flask(__name__) # Configure upload file path flaskapp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.secret_key = 'This is your secret key to utilize session in Flask'  @app.route('/', methods=['GET', 'POST'])def uploadFile():    if requesthod == 'POST':      # upload file flask        f = request.files.get('file')         # Extracting uploaded file name        data_filename = secure_filename(f.filename)         f.save(os.path.join(app.config['UPLOAD_FOLDER'],                            data_filename))         session['uploaded_data_file_path'] =        os.path.join(app.config['UPLOAD_FOLDER'],                     data_filename)         return render_template('index2.html')    return render_template("index.html")  @app.route('/show_data')def showData():    # Uploaded File Path    data_file_path = session.get('uploaded_data_file_path', None)    # read csv    uploaded_df = pd.read_csv(data_file_path,                              encoding='unicode_escape')    # Converting to html Table    uploaded_df_html = uploaded_df.to_html()    return render_template('show_csv_data.html',                           data_var=uploaded_df_html)  if __name__ == '__main__':    app.run(debug=True)

Output:

We can see the CSV file uploaded has been stored in ‘staticFiles’ folder with ‘uploads’ as a sub-folder.

Uploading and Reading a CSV File in Flask

 

My Personal Notes arrow_drop_up


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3